<template>
  <div id="leaflet-map" ref="mapContainer"></div>

</template>

<script>
import 'leaflet/dist/leaflet.css'
import {ElMessage} from "element-plus";
import L from "leaflet"
import request from "../../../utils/request.js";
import { selectByAreaCode } from "../../../api/map";
import { selectByGroupAndArea } from "../../../api/video";
import homeIcon from '../../../assets/icon-camera.png'

export default {
  name: "Leaflet",
  data() {

  },
  mounted() {
    this.init()
  },
  methods: {
    init() {
      let me = this;
      //加载区县GEO-JSON
      // request.get("/api/geo/selectByAreaCode")
      selectByAreaCode().then((resp) => {
          let geojson = resp.data.data;
          me.initMap(geojson); //初始化地图
          me.loadCameras('')
      })
    },
    initMap(geojson) {
      //中心点
      let me=this
      let center = [geojson[0].centerLat, geojson[0].centerLon];
      //创建地图
      this.map = L.map('leaflet-map', {
        center: center, //中心点
        zoom:this.getZoom(), //初始放大系数
        crs: L.CRS.EPSG4326, //wsg84坐标系
        attributionControl: false // 移除右下角leaflet标识
      });
      L.control.zoom({
        zoomInTitle:'放大',
        zoomOutTitle:'缩小',
      }).addTo(this.map)
      //地区图层组
      let areaLayer = L.layerGroup();
      this.map.addLayer(areaLayer);
      //区县
      for (let i = 1; i < geojson.length; i++) {
        let geoObject = JSON.parse(geojson[i].geoJson); //服务端返回的是字符串JSON，转换为对象
        //创建一个geoJSON图层加入到地区图层组
        let layer = L.geoJSON(geoObject, {
          onEachFeature: function (feature, layer) {
            layer.options.color = '#A2EEFF' //边框颜色
            layer.options.weight = 1 //边框宽度
            layer.options.fillColor = '#42DFFC'; //填充色
            layer.options.fillOpacity = 0.4;//半透明
          }
        });
        //将当前区县加入区县图层组
        areaLayer.addLayer(layer);

        /**
         * 在地图上做标记，因为标记有特殊背景，因此使用DivIcon
         */
          //地图标记的标注图标
        let icon = L.divIcon({
            className: 'marker-div-icon',
            html: geojson[i].name,
            iconAnchor: [60, 50] //偏移量，尽量调整到区县的中间
          });
        //标记的坐标
        //创建标记，加入地图，绑定事件
        let markerPos = [geojson[i].centerLat, geojson[i].centerLon];
          L.marker(markerPos, {
            icon: icon,
            riseOnHover: true
          }).addTo(this.map)
            .on('click', function () {//Marker事件
              console.log(geojson[i])
            })
        /**
         * png图标示例
         */
       /* let cameraIcon =  L.icon({
          iconUrl: '/src/assets/icon-camera.png',
          iconSize: [30, 30]
        });
        L.marker(markerPos, {
          icon: cameraIcon
        }).addTo(this.map)
          .on('click', function () {//Marker事件
            console.log(geojson[i])
            me.$emit('playVideo',geojson[i])
          })*/
      }
    },
    /**
     * 加载视频设备分布图
     */
    loadCameras(areaCode) {
      let me=this
      if (!this.map) { //地图未初始化
        return;
      }
      //用于存放视频设备图标的图层组
      if (!this.cameraLayers) {
        this.cameraLayers = L.layerGroup().addTo(this.map);
      } else {
        this.cameraLayers.removeAll();//如果已经有设备图标，则清空
      }

      //图标
      let cameraIcon =  L.icon({
        // iconUrl: '/src/assets/icon-camera.png',
        iconUrl: homeIcon,
        iconSize: [40, 40]
      });
      //加载视频
      selectByGroupAndArea({areaCode: areaCode}).then(resp=>{
        let cameras = resp.data.data;
        for(let i = 0; i < cameras.length; i++) {
          L.marker([cameras[i].latitude, cameras[i].longitude], {
            icon: cameraIcon
          })
            .addTo(this.cameraLayers).bindTooltip(cameras[i].deviceName + (cameras[i].online ? '<span style="color: #55a532">（在线）</span>': '<span style="color: #f1740c">（离线）</span>'))
            .on('click', function() {
              // alert('可以在这里控制视频播放' + cameras[i].deviceCode)
              if (cameras[i].online){
                me.$emit('playVideo',cameras[i].deviceCode)
              }

            })
        }
      })
      /*request.get("/api/camera/selectByGroupAndArea", {params: {areaCode: areaCode}})
        .then((resp) => {
          console.log('resp-----',resp)
          if (resp.data.status===200){
            let cameras = resp.data.data;
            for(let i = 0; i < cameras.length; i++) {
              L.marker([cameras[i].latitude, cameras[i].longitude], {
                icon: cameraIcon
              })
                .addTo(this.cameraLayers)
                .on('click', function() {
                  // alert('可以在这里控制视频播放' + cameras[i].deviceCode)
                  if (cameras[i].online){
                    me.$emit('playVideo',cameras[i])
                  }

                })
            }
          }
        })*/
    },
    /**
     * 可以通过不断优化这里的参数，适配不同的分辨率^_^
     * @return {number}
     */
    getZoom() {
      let width = this.$refs.mapContainer.clientWidth;
      if (width < 600) {
        return 9;
      } else if (width < 2000) {
        return 10
      } else {
        return 11
      }
    }
  }
}

</script>
<style>
body .leaflet-control {
  opacity: 0.1;
  position: absolute;
  top: 50px;
}

body .marker-div-icon {
  width: 60px !important;
  height: 50px !important;
  background: url("../../../assets/marker-1.png") no-repeat;
  background-size: 100% 100%;
  padding-top: 7px;
  text-align: center;
  color: #00f9ff;
}

body .marker-div-icon:hover {
  background: url("../../../assets/marker-2.png") no-repeat;
  background-size: 100% 100%;
  color: #FCEE4F;
}

</style>
<style scoped>
#leaflet-map {
  width: 100%;
  height: 100%;
}

.leaflet-container {
  background-color: transparent;
}

</style>
